package com.kira.scaffoldmvc.Interceptor;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取Content-Length头信息
        String contentLength = request.getHeader("content-length");
        if (contentLength == null || contentLength.isEmpty()) {
            log.info("未获取到Content-Length头信息");
            log.info("有可能是非法请求");
        }

        int length;
        try {
            length = Integer.parseInt(contentLength);
        } catch (NumberFormatException e) {
            log.error("Content-Length格式错误: {}", contentLength);
            return true;
        }

        // 流量大小判断
        if (length < 1048576) { // 1MB
            log.info("1mb以内的流量");
        } else if (length >= 1048576 && length < 10485760) { // 1MB-10MB
            log.info("1mb到10mb的流量");
        } else if (length >= 10485760 && length < 20971520) { // 10MB-20MB
            log.info("10mb到20mb的流量");
        } else if (length >= 20971520 && length < 31457280) { // 20MB-30MB
            log.info("20mb到30mb的流量");
        } else if (length >= 31457280 && length < 41943040) { // 30MB-40MB
            log.info("30mb到40mb的流量");
        } else if (length >= 41943040 && length <= 52428800) { // 40MB-50MB
            log.info("40mb到50mb的流量");
        } else {
            // 超过50MB时返回错误状态码和信息
            log.warn("超过50mb的流量，拒绝处理");
            response.sendError(
                    HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "请求体过大，超过50MB限制"
            );
            return false; // 阻止请求继续处理
        }

        // 放行请求
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 后续处理逻辑
    }
}
